import 'dart:io';

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:tencent_cloud_chat_demo/utils/api/sticker.dart';
import 'package:tencent_cloud_chat_demo/utils/path.dart';
import 'package:tencent_cloud_chat_demo/utils/picture.dart';

import 'custom_sticker_entity.dart';

class EmojiDatabase {
  static Database? _db;

  static Future<Database> get database async {
    if (_db != null) return _db!;
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'emoji.db');

    _db = await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE emoji (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            file_path TEXT NOT NULL,
            keywords TEXT UNIQUE,
            created_at INTEGER,
            file_id INTEGER
          );
        ''');
      },
    );

    return _db!;
  }
}

Future<void> clearEmojis() async {
  final db = await EmojiDatabase.database;

  await db.transaction((txn) async {
    // 1. 清空表
    await txn.delete('emoji');

    // 清空文件夹
    final customstickerDir = Directory('${AppPath.documentPath}/customsticker');
    if (customstickerDir.existsSync()) {
      await customstickerDir.delete(recursive: true);
    }
    await customstickerDir.create(recursive: true);
  });
}

Future<void> initEmoji() async {
  clearEmojis();
  // final customstickerDir = Directory('${AppPath.documentPath}/customsticker');
  // if (customstickerDir.existsSync()) {
  //   return;
  // }
  // await customstickerDir.create(recursive: true);
  final allStickers = await CustomSitckerAPI.getAllSticker();
  if (allStickers == null) {
    return;
  }

  final urls = allStickers.map((e) {
    final name = (e['url'] as String).split('/').last;
    return Urlss(
        url: e['url'],
        name: name,
        createdAt: DateTime.parse(e['create_time']).microsecond,
        fileId: e['id']);
  }).toList();
  final f = await downloadEmojisToCustomStickerDir(urls);
  f.forEach((file) async {
    insertEmoji(
      file.url,
      file.fileId!,
      keywords: file.name,
    );
  });
}

Future<int> insertEmoji(String filePath, int fileId, {String? keywords}) async {
  final db = await EmojiDatabase.database;
  return await db.insert(
    'emoji',
    {
      'file_path': filePath,
      'keywords': keywords ?? '',
      'created_at': DateTime.now().millisecondsSinceEpoch,
      'file_id': fileId,
    },
    conflictAlgorithm: ConflictAlgorithm.ignore, // 🚀 遇到冲突时忽略插入
  );
}

Future<List<Map<String, dynamic>>> getAllEmojis() async {
  final db = await EmojiDatabase.database;
  return await db.query('emoji', orderBy: 'created_at DESC');
}

Future<List<Map<String, dynamic>>> searchEmojis(String keyword) async {
  final db = await EmojiDatabase.database;
  return await db.query(
    'emoji',
    where: 'keywords LIKE ?',
    whereArgs: ['%$keyword%'],
  );
}

Future<int> deleteEmoji(int id) async {
  final db = await EmojiDatabase.database;
  return await db.delete('emoji', where: 'file_id = ?', whereArgs: [id]);
}
